package com.yc.starter.upload.action;

import com.yc.starter.upload.config.UploadMapper;
import com.yc.starter.upload.config.UploadProperties;
import com.yc.starter.upload.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.UUID;

/**
 * @author navy
 * @company 源辰信息
 * @date 2024/9/10
 * @email haijunzhou@hnit.edu.cn
 */
@RestController
@RequestMapping("upload")
@Slf4j
public class UploadAction {

    @Autowired
    UploadProperties properties;

    @RequestMapping("props")
    UploadProperties props(){
        return properties;
    }

    @PostMapping("upload")
    Result upload(@RequestParam("file") MultipartFile file, String type) throws IOException {
        try{
            UploadMapper um = properties.getMappers()
                    .stream()
                    .filter(a->a.getType().equals(type))
                    .findFirst()
                    .get();
            String prefix = UUID.randomUUID().toString();
            String suffix = file.getOriginalFilename().replaceAll(".+(\\.[^\\.])","$1");
            String filename = prefix + suffix;
            String filepath = um.getDiskPath() + filename;
            log.debug("filepath = " + filepath);
            file.transferTo(new File(filepath));
            String webPath = um.getWebPath() + filename;
            return new Result(1, "文件上传成功!", webPath);
        }catch (NoSuchElementException e){
            return new Result(-1, "没有定义该类型的上传文件配置", null);
        }
    }
}
